<template>
  <div class="app-container" >
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['mt:shop:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['mt:shop:export']">导出</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button type="cyan" icon="el-icon-coordinate" size="mini" @click="accredit">美团授权</el-button>-->
<!--      </el-col>-->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="店铺编码" align="center" prop="code" width="70"/>
      <el-table-column label="店铺" align="center" prop="name" width="200"/>
      <el-table-column label="ERP组织" align="center" prop="orgName" />
      <el-table-column label="ERP部门" align="center" prop="deptName" />
      <el-table-column label="订单发起人" align="center" prop="sysusernickname" width="75"/>
      <el-table-column label="销售客户" align="center" prop="customerName" width="60"/>
      <el-table-column label="拉取日期" align="center" prop="pulldate" width="80">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pulldate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="拉取状态" align="center" prop="pullState" width="60"/>
      <el-table-column label="推送日期" align="center" prop="pushdate" width="80"/>
      <el-table-column label="推送状态" align="center" prop="pushState" width="60"/>
      <el-table-column label="状态" align="center" prop="status" width="40"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mt:shop:edit']"
          >修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-refresh" @click="pushData(scope.row)">同步</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

<!--    店铺同步数据对话框-->
    <el-dialog title="同步数据" :visible.sync="open1" width="450px" append-to-body v-loading="pushLoading">
      <el-form ref="formPu" :model="pushList" label-width="110px" :inline="true" >
        <el-form-item label="店铺名称:" prop="name">
          <span>{{pushList.name}}</span>
        </el-form-item>
        <br>
        <el-form-item label="拉取开始时间:" prop="pulldate">
          <span>{{pushList.pulldate}}</span>
        </el-form-item>
        <br>
        <el-form-item label="拉取结束时间:" prop="enddate">
          <el-date-picker v-model="pushList.enddate" value-format="yyyy-MM-dd" size="small" type="date" placeholder="请选择拉取结束时间"></el-date-picker>

<!--          <el-date-picker-->
<!--            v-model="pushList.date"-->
<!--            type="datetimerange"-->
<!--            range-separator="至"-->
<!--            start-placeholder="拉取开始日期"-->
<!--            end-placeholder="拉取结束日期">-->
<!--          </el-date-picker>-->

<!--          <el-date-picker-->
<!--            v-model="pushList.date"-->
<!--            type="daterange"-->
<!--            align="right"-->
<!--            unlink-panels-->
<!--            range-separator="至"-->
<!--            start-placeholder="开始日期"-->
<!--            end-placeholder="结束日期"-->
<!--            :picker-options="pickerOptions">-->
<!--          </el-date-picker>-->

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="shopPullData()" >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改美团店铺对话框 -->
    <el-dialog title="修改店铺" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" :inline="true" >
        <el-form-item label="订单发起人" prop="sysusernickname">
          <el-select v-model="form.sysuserid" size="small" placeholder="请选择订单发起人" clearable filterable>
            <el-option v-for="item in users" :label="item.nickName" :value="item.userId" :key="item.userId" @click.native="userChange($event,item)"/>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="销售客户" prop="customerName">-->
<!--          <el-select v-model="form.customerName" size="small" filterable clearable>-->
<!--            <el-option />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="ERP组织" prop="orgName">
          <el-select v-model="form.orgId" size="small" clearable filterable placeholder="请选择组织">
            <el-option v-for="item in orgs" :label="item.name" :value="item.id" :key="item.id" @click.native="orgChange($event,item)"/>
          </el-select>
        </el-form-item>
        <el-form-item label="ERP部门" prop="deptName">
          <el-select v-model="form.deptId" clearable size="small" filterable placeholder="请选择部门">
            <el-option v-for="item in depts" :label="item.name" :value="item.id" :key="item.id" @click.native="deptChange($event,item)"/>
          </el-select>
<!--          <treeselect v-model="form.deptId" :options="depts" :show-count="true" placeholder="请选择部门" style="width: 200px" @click.native="deptChange($event)"/>-->
<!--          <el-tree :data="depts"></el-tree>-->
        </el-form-item>
        <el-form-item label="美团组织编码" prop="mtOrgcode">
          <el-input v-model="form.mtOrgcode" size="small" clearable placeholder="请输入美团组织编码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listShop, getShop, delShop, addShop, updateShop, exportShop,shopPull,mtAccredit } from "@/api/mt/shop";
import {findOrganizationList,getUserList,getCustomerList,} from '@/api/public'
import {listDept} from '@/api/system/employee'
import {treeselect} from '@/api/system/dept'
import Treeselect from "@riophae/vue-treeselect";
import { parseTime } from '@/utils/ruoyi'
// import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "mtShop",
  components: {
    // Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      pushLoading:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 美团店铺表格数据
      shopList: [],
      pushList:{},
      orgs:[],
      depts:[],
      users:[],
      customers:[],
      // 弹出层标题
      title: "",
      open1:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        orgId: null,
        orgName: null,
        mtOrgid: null,
        sysuserid: null,
        sysusernickname: null,
        deptId: null,
        deptName: null,
        customerId: null,
        customerName: null,
        whinAsyndate: null,
        whoutAsyndate: null,
        foodconsumAsyndate: null,
        pulldate: null,
        pullState: null,
        status: null,
      },
      // pickerOptions:{
      //   shortcuts: [{
      //     text: '最近一周',
      //     onClick(picker) {
      //       const end = new Date();
      //       const start = new Date();
      //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      //       picker.$emit('pick', [start, end]);
      //     }
      //   }, {
      //     text: '最近一个月',
      //     onClick(picker) {
      //       const end = new Date();
      //       const start = new Date();
      //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      //       picker.$emit('pick', [start, end]);
      //     }
      //   }, {
      //     text: '最近三个月',
      //     onClick(picker) {
      //       const end = new Date();
      //       const start = new Date();
      //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      //       picker.$emit('pick', [start, end]);
      //     }
      //   }]
      // },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getOrgs();
    this.getUsers();
    this.getCustomers();
  },
  methods: {
    accredit(){
      mtAccredit().then(response=>{
        if (response.code==200){
          window.open(response.msg)
        }
      })
    },
    shopPullData(){
      if (!this.pushList.pulldate) return this.msgError('开始时间为空')
      if (!this.pushList.enddate){
        return this.msgError('请选择结束时间');
      }
      if (this.pushList.enddate<=this.pushList.pulldate){
        return this.msgError('结束时间必须大于开始时间')
      }
      if (this.pushList.pulldate){
        let startArray=this.pushList.pulldate.split("-");
        let endArray=this.pushList.enddate.split("-");
        if (startArray[0]!==endArray[0] || startArray[1]!==endArray[1]){
          return this.msgError('结束时间和开始时间必须在同一月')
        }
      }
      let data={
        id:this.pushList.id,
        pulldate:this.pushList.pulldate,
        pulldateEnd:this.pushList.enddate,
      }

      this.pushLoading=true;
      shopPull(data).then(response=>{
        if (response.code==200){
          this.pushLoading=false;
          this.msgSuccess('操作成功')
          this.open1=false;
          this.getList()
        }
      }).catch(()=>{
        this.msgError('操作失败');
        this.pushLoading=false;
      })
    },
    getLastDayOfMonth(year,month){
      return new Date(year,Number(month),0).getDate();
    },
    pushData(row){
      this.pushList={};
      this.pushList=row;
      if (row.pulldate){
        let startArray=(row.pulldate || "").split("-");
        let date=this.getLastDayOfMonth(startArray[0],startArray[1])
        // console.log(`${startArray[0]}年${startArray[1]}月的最后一天为${date}`)
        // this.pushList.enddate=startArray[0]+'-'+startArray[1]+'-'+date;
        //数据双向绑定失效时使用set     当月最后一天
        // this.$set(this.pushList,'enddate',startArray[0]+'-'+startArray[1]+'-'+date)
        // 开始时间后一天
        let date1=new Date(row.pulldate).getDate()+1
        this.$set(this.pushList,'enddate',startArray[0]+'-'+startArray[1]+'-'+date1)
        // console.log('时间：',startArray[0]+'-'+startArray[1]+'-'+date)
      }
      this.open1=true;
    },
    getCustomers(){
      getCustomerList().then(response=>{
        this.customers=response.data;
      })
    },
    userChange($event,item){
      this.form.sysusernickname=item.nickName;
    },
    getUsers(){
      getUserList().then(response=>{
        this.users=response.data;
      })
    },
    deptChange($event,item){
      this.form.deptName=item.name;
    },
    orgChange($event,item){
      this.form.deptId=null;
      this.form.orgName=item.name;
      listDept({orgguid:item.guid}).then(response=>{
        this.depts=response.data;
      })
    },
    getOrgs(){
      findOrganizationList().then(response=>{
        this.orgs=response.data;
      })
    },
    /** 查询美团店铺列表 */
    getList() {
      // let a=new Date();
      //获取昨天时间
      // a.setTime(a.getTime()-24*60*60*1000);
      // let b=a.getFullYear()+'-'+(a.getMonth()+1)+'-'+a.getDate();
      // console.log('time:',b)
      this.loading = true;
      listShop(this.queryParams).then(response => {
        this.shopList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open1=false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        orgId: null,
        orgName: null,
        mtOrgid: null,
        sysuserid: null,
        sysusernickname: null,
        deptId: null,
        deptName: null,
        customerId: null,
        customerName: null,
        whinAsyndate: null,
        whoutAsyndate: null,
        foodconsumAsyndate: null,
        pulldate: null,
        pullState: null,
        status: 0,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加美团店铺";
    },
    /** 修改按钮操作 */
     async handleUpdate(row) {
      // this.reset();
      const id = row.id || this.ids
      await getShop(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改美团店铺";
      });
      this.orgs.map(item=>{
        if (item.id==this.form.orgId){
          this.form.orgguid=item.guid;
        }
      })
      listDept({orgguid:this.form.orgguid}).then(response=>{
        this.depts=response.data;
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateShop(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addShop(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delShop(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有美团店铺数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportShop(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
